<template>
  <!-- 新增摄像头 表单 -->
  <a-modal
    v-model:open="visible"
    :title="isEdit ? '编辑摄像头' : '新增摄像头'"
    @ok="handleOk"
    class="addStation"
    destroyOnClose
    :width="480"
    @cancel="cancel"
    centered
  >
    <a-form
      :model="form"
      :rules="rules"
      layout="inline"
      :labelCol="labelCol"
      ref="formRef"
    >
      <a-form-item v-if="isEdit" label="电站名称：" name="stationId">
        <a-select
          v-model:value="stationId"
          class="formInput"
          placeholder="请选择"
        >
          <a-select-option
            v-for="item in supplierList"
            :value="item.stationId"
            :key="item.stationId"
          >
            {{ item.stationName }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item v-else label="电站名称：">
        {{ stationInfo.name }}
      </a-form-item>
      <a-form-item name="wiringDiagramUrl">
        <template #label>
          摄像头照片
          <a-tooltip v-model:open="tipvisible">
            <template #title>
              <p>点击可自动识别并填充所上传照片的序列号和验证码</p>
              <p>
                图片要求：二维码清晰可见，保留IMEI、进网试用区域、摄像头参数区域
              </p>
              详见<a-button type="link" size="small" @click="handleImgTip"
                >摄像头照片示例</a-button
              >
            </template>
            <ExclamationCircleOutlined class="tipIcon" />
          </a-tooltip>
        </template>
        <a-upload
          v-model:file-list="fileList"
          name="file"
          list-type="picture-card"
          class="addUpload"
          accept=".JPEG,.PNG"
          :max-count="1"
          :action="handleImport"
          :headers="headers"
          method="post"
          :preview-file="previewFile"
          :before-upload="beforeUpload"
          @change="handleUploadChange"
          @remove="handleRemove"
        >
          <div>
            <loading-outlined v-if="loading"></loading-outlined>
            <plus-outlined v-else></plus-outlined>
            <div class="ant-upload-text">上传</div>
          </div>
        </a-upload>
        <div class="uploadTip">
          支持JPEG、PNG等格式，上传数量不得超过1个，大小不得超过10M
        </div>
      </a-form-item>
      <a-form-item label="摄像头序列号：" name="serialNo">
        <a-input
          v-model:value="form.serialNo"
          class="formInput"
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item label="摄像头验证码：" name="validateCode">
        <a-input
          v-model:value="form.validateCode"
          class="formInput"
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item label="摄像头名称：" name="name">
        <a-input
          v-model:value="form.name"
          class="formInput"
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item label="是否加密：">
        <a-select
          ref="select"
          :value="0"
          class="formInput"
          disabled
          allow-clear
        >
          <a-select-option :value="1">是</a-select-option>
          <a-select-option :value="0">否</a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
    <template #footer>
      <div class="footerBar">
        <a-button key="back" @click="cancel">取消</a-button>
        <a-button
          key="submit"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确认</a-button
        >
      </div>
    </template>
  </a-modal>

  <a-modal
    v-model:open="imgTipvisible"
    title="照片示例"
    destroyOnClose
    :width="600"
    centered
  >
    <img :src="teach6" class="teachImg" />
    <template #footer>
      <div class="footerBar">
        <a-button
          key="submit"
          type="primary"
          :loading="loading"
          @click="imgTipvisible = false"
          >关闭</a-button
        >
      </div>
    </template>
  </a-modal>
</template>
<script setup>


import teach6 from "@/assets/teach6.png";
import storage from "@/utils/storage"
const $api = inject("$api");
const props = defineProps({
  addMonitorVisible: {
    type: Boolean,
    default: false,
  },
  rowData: {
    type: Object,
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
  editType: {
    type: String,
  },
  stationInfo: {
    type: Number,
  },
  supplierList: {
    type: Array,
  },
});
const loading = ref(false);
const visible = ref(props.addMonitorVisible);
const tipvisible = ref(false);
const imgTipvisible = ref(false);
const fileList = ref([]);
const stationId = ref(null);
const emits = defineEmits(["update:addMonitorVisible", "getSupplierPage"]);
watch(
  () => props.addMonitorVisible,
  (val) => {
    visible.value = val;
    if (val && props.isEdit) {
      getCompanyStationtList();
      form.value = {
        ...props.rowData,
      };
      stationId.value = props.rowData.stationId;
    }
  }
);
const userInf = storage.getItem("USER_INFO")
const headers = ref({
  Authorization: "Bearer " + userInf.access_token,
})
const labelCol = { style: { width: "120px" } };
const formRef = ref(null);
const form = ref({
  serialNo: null,
  validateCode: null,
  name: null,
});
const rules = ref({
  stationId: [
    {
      required: true,
      message: "请选择",
      trigger: "blur",
    },
  ],
  name: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
  ],
  serialNo: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
  ],
  validateCode: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
  ],
});

const cancel = () => {
  emits("update:addMonitorVisible", false);
  form.value = {
    serialNo: null,
    validateCode: null,
    name: null,
  };
  fileList.value = [];
  formRef.value.clearValidate();
};
const handleImport = async (val) => {
  return `${$api.qrcodeData().url}`;
};
const decodeResult = ref({});
const handleUploadChange = (fileReponse) => {
  if (fileReponse.file?.response?.code === 0) {
    // decodeResult 是萤石云解析二维码后的结果，用 \r 分割，第二个数值即序列号，第三个数值即验证码
    decodeResult.value =
      fileReponse.file.response.data.decodeResult.split("\r");
    if (decodeResult.value.length) {
      form.value.serialNo = decodeResult.value[1];
      form.value.validateCode = decodeResult.value[2];
    }
  }
};
const handleSubmit = () => {
  formRef.value
    .validate()
    .then(async () => {
      const params = {
        ...form.value,
        stationId: props.stationInfo.id,
        imageFileId: fileList.value[0]?.response?.data?.id,
      };
      if (props.isEdit) {
        // 编辑带上id
        params.id = props.rowData.id;
        params.stationId = stationId.value;
      }
      loading.value = true;
      let res;

      console.log('[ props.editType ]-275', props.editType)

      if (props.editType === "isContinue") {
        // 如果是 萤石云 配置按钮，调对应接口
        res = await $api.cameraContinue(params, "put");
      } else {
        res = await $api.cameraAdd(params, props.isEdit ? "put" : "post");
      }
      loading.value = false;
      if (res.code === 0) {
        message.success(props.isEdit ? "编辑成功" : "新增成功");
        cancel();
        emits("refreshList");
      }
    })
    .catch((error) => {
      console.log("error", error);
    });
};
const handleImgTip = () => {
  tipvisible.value = false;
  imgTipvisible.value = true;
};
const stationtList = ref([]);
const getCompanyStationtList = async () => {
  const res = await $api.companyStationtList();
  if (res.code === 0) {
    stationtList.value = res.data;
  }
};
</script>

<style lang="less" scoped>
.form {
  padding: 0 40px;
  margin-top: 30px;
}
.formInput,
.formSelect {
  width: 300px;
}
.ant-form-item {
  margin-top: 20px;
}
.footerBar {
  text-align: center;
  margin-top: 30px;
}
.addUpload {
  width: 250px;
}
.uploadTip {
  width: 300px;
  color: #999;
  font-size: 12px;
}
.teachImg {
  width: 550px;
}
.tipIcon {
  margin-left: 5px;
}
</style>